package fr.babostesting.stage3 
{
	import com.greensock.easing.Back;
	import com.greensock.easing.Strong;
	import com.greensock.TweenMax;
	import flash.geom.Point;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import fr.babos.graphic.tools.BitmapCache;
	import fr.babos.utils.ArrayUtils;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	
	/**
	 * ...
	 * @author ...
	 */
	public class ListBaseClass extends Sprite 
	{
		protected var _container:Sprite;
		
		protected var _elements:Array;
		protected var _twitterData:Object;
		protected var _currentPosition:Point;
		protected var _delta:Number = 0;
		
		protected var _totalElementToShow:int;
		protected var _bitmapCache:BitmapCache;
		
		public function ListBaseClass ()
		{
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		protected function init (event:Event):void
		{
			_totalElementToShow = 160;
			
			var serviceURL:String = "http://search.twitter.com/search.json?q=as3&rpp=" + _totalElementToShow.toString(10) + "&include_entities=true&result_type=mixed";
			
			var urlLoader:URLLoader = new URLLoader(new URLRequest(serviceURL));
			urlLoader.addEventListener("complete", dataLoadedHandler);
			trace("loading");
		}
		
		public function dataLoadedHandler (event:Object):void
		{
			(event.currentTarget as URLLoader).removeEventListener("complete", dataLoadedHandler);
			
			trace("loaded");
			
			_twitterData = JSON.parse((event.currentTarget as URLLoader).data);
			
			if (_twitterData["results"] != null)
				_twitterData = _twitterData.results;
			
			_totalElementToShow = _twitterData.length;
			
			_bitmapCache = new BitmapCache();
			
			_elements = [];
			
			_container = new Sprite();
			
			addChild(_container);
			
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			addEventListener(TouchEvent.TOUCH, touchEventHandler);
		}
		
		protected function touchEventHandler (event:TouchEvent):void
		{
			var touch:Touch = event.getTouch(stage);
			var location:Point = touch.getLocation(stage);
			
			var minPosition:int = 0;
			var maxPosition:int = - (_totalElementToShow) * 100 + stage.stageHeight;
			
			if (touch.phase == TouchPhase.BEGAN)
			{
				_currentPosition = location.clone();
				
				TweenMax.killTweensOf(_container);
				
				_delta = 0;
			}
			else if (touch.phase == TouchPhase.MOVED)
			{
				_delta = location.y - _currentPosition.y;
				
				if (_container.y > minPosition || _container.y < maxPosition)
				{
					_delta /= 2;
				}
				
				_container.y = int(_container.y + _delta - .5);
				//_container.y += _delta;
				
				_currentPosition = location.clone();
			}
			else if (touch.phase == TouchPhase.ENDED)
			{
				if (_delta != 0)
				{
					trace(_delta);
					
					var destination:Number = _container.y + _delta * 6;
					
					var ease:Function = Strong.easeOut;
					
					if (destination > minPosition)
					{
						destination = minPosition;
						
						if (_container.y < minPosition)
							ease = Back.easeOut;
					}
					else if (destination < maxPosition)
					{
						destination = maxPosition;
						
						if (_container.y > maxPosition)
							ease = Back.easeOut;
					}
					
					TweenMax.to(_container, .8, {
						roundProps: ["y"],
						y: destination,
						ease: ease
					});
				}
			}
		}
		
		protected function enterFrameHandler (event:Event):void
		{
			updateElements();
		}
		
		protected function updateElements ():void
		{
			var start:int = int(- _container.y / 100) - 1;
			var end:int = start + Math.ceil(stage.stageHeight / 100) + 1;
			
			//trace(">", start, "/", end);
			
			var i:int = start;
			var element:LineElement;
			
			for each (element in _elements)
			{
				if (element.index < start || element.index > end)
				{
					trace("DELETE", element.index);
					
					_elements = ArrayUtils.deleteElement(_elements, element);
					
					element.removeFromParent(true);
				}
			}
			
			while (i <= end)
			{
				element = null;
				
				for each (var currentElement:LineElement in _elements)
				{
					if (currentElement.index == i)
					{
						element = currentElement;
						break;
					}
				}
				
				if (element == null)
				{
					element = needElementAt(i);
					
					if (element != null)
					{
						trace("ADD ELEMENT", i);
						
						_elements.push(element);
						
						element.index = i;
						
						element.y = i * 100;
						
						_container.addChild(element);
					}
				}
				
				i ++;
			}
		}
		
		protected function needElementAt (pAt:int):LineElement
		{
			var item:Object
			
			if (pAt in _twitterData)
			{
				item = {
					avatar: _twitterData[pAt].profile_image_url,
					username: _twitterData[pAt].from_user_name,
					text: _twitterData[pAt].text
				};
			}
			
			return new LineElement(item, _bitmapCache);
		}
	}
}